<template>
    <div>
        <!-- 搜索 -->
        <el-form :inline="true">
            <el-form-item label="姓名">
                <el-input v-model="queryInfo.name" placeholder="请输入搜索姓名" clearable @clear="loadUsers(true)"></el-input>
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="queryInfo.phone" placeholder="请输入电话" clearable @clear="loadUsers(true)"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="queryInfo.status" placeholder="全部" clearable @clear="loadUsers(true)">
                    <el-option label="启用" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loadUsers(true)">查询</el-button>
                <el-button type="success" @click="addDialogVisible = true">添加</el-button>
                <el-button type="danger" @click="removeMultiple">批量删除</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="userList" border stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" type="index" width="55"></el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="电话" prop="phone"></el-table-column>
            <el-table-column label="地址" prop="address"></el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" @change="modifyStatus(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column>
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="showEditDialog(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="removeById(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 20, 50]" :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDialogClosed">
            <el-form :model="addForm" ref="addFormRef" :rules="addFormRules">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="addForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="addForm.address"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 编辑用户的对话框 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogVisible" @close="editDialogClosed">
            <el-form :model="editForm" ref="editFormRef" :rules="editFormRules">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="editForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="editForm.address"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 用户列表
            userList: [],
            // 查询条件
            queryInfo: {
                pageNum: 1,
                pageSize: 5,
                name: '',
                phone: '',
                status: null
            },
            // 总记录数
            total: 0,
            // 添加用户对话框的显示和隐藏
            addDialogVisible: false,
            // 添加用户的表单数据
            addForm: {
                name: '',
                phone: '',
                address: ''
            },
            // 添加用户的表单验证规则
            addFormRules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    // { pattern: /^1[3456789]\d{9}$/, message: '电话格式不正确', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' }
                ],
            },
            // 编辑用户对话框的显示和隐藏
            editDialogVisible: false,
            // 编辑用户的表单数据
            editForm: {
                id: '',
                name: '',
                phone: '',
                address: ''
            },
            // 编辑用户的表单验证规则
            editFormRules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { pattern: /^1[3456789]\d{9}$/, message: '电话格式不正确', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' }
                ],
            },
            // 复选框选中的值
            multipleSelection:[]
        }
    },
    created() {
        this.loadUsers()
    },
    methods: {
        // 加载用户数据
        async loadUsers(flag) {
            // 如果flag为true，说明是查询操作，把页码设置为1，目的是只要是查询操作都从第一页开始查
            if (flag) {
                this.queryInfo.pageNum = 1
            }

            const { data: res } = await this.$http.get('/api/user/queryByPage', {
                params: this.queryInfo
            })
            this.userList = res.data.list
            this.userList.forEach(item => {
                item.status = item.status === 0 ? true : false
            })
            this.total = res.data.total
        },
        // 根据id删除用户
        removeById(id) {
            this.$confirm('确定要删除吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`/api/user/remove/${id}`)
                if (res.status != 200) {
                    this.$message.error('删除失败!')
                }
                this.$message.success('删除成功!')

                // 如果删除后，当前页没有数据了，则查找上一页的数据
                this.loadUsers().then(() => {
                    if(this.userList.length==0 && this.queryInfo.pageNum>1){
                        this.queryInfo.pageNum--
                        this.loadUsers()
                    }
                })
            }).catch(() => {
                this.$message.info('取消删除!')
            });
        },
        // 监听页大小的改变
        handleSizeChange(val) {
            this.queryInfo.pageSize = val
            this.loadUsers()
        },
        // 监听页码的改变
        handleCurrentChange(val) {
            this.queryInfo.pageNum = val
            this.loadUsers()
        },
        // 添加用户
        addUser() {
            // 先进行表单校验
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) {
                    return
                }

                // 表单校验通过，发送请求添加用户
                const { data: res } = await this.$http.post('/api/user/add', this.addForm)
                if (res.status != 200) {
                    return this.$message.error(res.msg)
                }
                // 提示添加成功
                this.$message.success('添加成功!')
                // 关闭对话框
                this.addDialogVisible = false
                // 重新加载用户列表
                this.loadUsers()
            })
        },
        // 监听添加对话框的关闭事件
        addDialogClosed() {
            // 清空表单数据
            this.$refs.addFormRef.resetFields()
        },
        // 显示编辑对话框
        async showEditDialog(id) {
            const { data: res } = await this.$http.get(`/api/user/query/${id}`)
            if (res.status != 200) {
                return this.$message.error('获取用户信息失败!')
            }
            this.editForm = res.data

            this.editDialogVisible = true
        },
        // 监听编辑对话框的关闭事件
        editDialogClosed() {
            // 清空表单数据
            this.$refs.editFormRef.resetFields()
        },
        // 编辑用户
        editUser() {
            // 先进行表单校验
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) {
                    return
                }

                // 表单校验通过，发送请求添加用户
                const { data: res } = await this.$http.put('/api/user/modify', this.editForm)
                if (res.status != 200) {
                    return this.$message.error('修改失败!')
                }
                // 提示添加成功
                this.$message.success('修改成功!')
                // 关闭对话框
                this.editDialogVisible = false
                // 重新加载用户列表
                this.loadUsers()
            })
        },
        // 修改用户的状态
        async modifyStatus(user){
            const {data:res} = await this.$http.put(`/api/user/modifyStatus/${user.id}/${user.status?0:1}`)
            if(res.status != 200){
                return this.$message.error('修改状态失败!')
            }
            this.$message.success('修改状态成功!')
        },
        // 监听复选框的改变
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 批量删除
        removeMultiple(){
            if(this.multipleSelection.length === 0){
                return this.$message.error('请选择要删除的用户!')
            }
            this.$confirm('确定要删除吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const ids = this.multipleSelection.map(item => item.id)
                const { data: res } = await this.$http.delete(`/api/user/removeBatch`, {
                    data: ids
                })
                if (res.status != 200) {
                    this.$message.error('删除失败!')
                }
                this.$message.success('删除成功!')

                // 如果删除后，当前页没有数据了，则查找上一页的数据
                this.loadUsers().then(() => {
                    if(this.userList.length==0 && this.queryInfo.pageNum>1){
                        this.queryInfo.pageNum--
                        this.loadUsers()
                    }
                })
            }).catch(() => {
                this.$message.info('取消删除!')
            });
        }
    }
}
</script>

<style scoped>
.el-pagination {
    text-align: center;
}
</style>